<template>
  <div class="logincontend" :style="{backgroundImage: `url(${loginBg})`}" v-loading="loading" :element-loading-text="loadingText">
    <el-row :gutter="120">
      <el-col :xs="24" :sm="24" :md="12" :lg="16">
        <div style="margin-left: 5%">
          <h1 class="login-title">欢迎登录智慧资管运营后台</h1>
          <div>
            <el-link>
              <h3>智慧物业</h3>
            </el-link>
            <el-divider direction="vertical"></el-divider>
            <el-link>
              <h3>智慧租赁</h3>
            </el-link>
            <el-divider direction="vertical"></el-divider>
            <el-link>
              <h3>项目管理</h3>
            </el-link>
            <el-divider direction="vertical"></el-divider>
            <el-link>
              <h3>授权考核</h3>
            </el-link>
            <el-link type="primary" style="margin-left: 20px">
              <h2>智慧物业管理，提升价值共识</h2>
            </el-link>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="8">
        <el-card shadow="never" class="login-box">
          <div class="logoimg">
            <div class="name">智慧资管运营后台</div>
          </div>
          <el-divider />
          <el-tabs v-model="activeName">
            <el-tab-pane label="账号密码登录" name="first">
              <el-form class="form-wrapper" ref="loginForm" :model="loginForm" :rules="rules">
                <el-form-item prop="username">
                  <el-input type="text" clearable placeholder v-model.trim="loginForm.username" />
                </el-form-item>
                <el-form-item prop="password">
                  <el-input type="password" clearable placeholder="请输入密码" v-model.trim="loginForm.password" />
                </el-form-item>
                <el-form-item prop="code">
                  <el-input placeholder="请输入验证码" v-model="loginForm.code" @keyup.enter.native="onSubmit('loginForm')">
                    <template slot="append">
                      <img :src="codeUrl" @click="getCode" />
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item style="height: 70px"></el-form-item>
                <el-form-item>
                  <el-button size="medium" type="primary" v-on:click="onSubmit('loginForm')" style="width: 100%;background: #409EFF">登录</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- <el-tab-pane label="手机号码登录" name="second">
              <el-form class="form-wrapper" ref="mobileLoginForm" :model="mobileLoginForm" :rules="mobileLoginFormRules">
                <el-form-item prop="telnumber">
                  <el-input type="text" clearable placeholder="请输入手机号" v-model="mobileLoginForm.telnumber" />
                </el-form-item>
                <el-form-item prop="password">
                  <el-input type="password" clearable placeholder="请输入密码" v-model="mobileLoginForm.password" />
                </el-form-item>
                <el-form-item>
                  滑块验证
                  给子组件传数据，以及接受子组件改变后的数据
                  <slider ref="slider" v-bind:show="show" v-on:showChange="zdy($event)"></slider>
                </el-form-item>
                此为滑块控制的输入手机验证码部分
                <el-form-item prop="telcode" v-if="show">
                  <el-input size="medium" clearable placeholder="请输入手机验证码" v-model="mobileLoginForm.telcode" class="input-with-select">
                    <el-button size="mini" slot="append" @click="phoneCode()" style="background:#409EFF;color:#fff">获取验证码</el-button>
                  </el-input>
                </el-form-item>
                <el-form-item style="height: 30px"></el-form-item>
                <el-form-item>
                  <el-button size="medium" type="primary" @click="PhoneOnSubmit('mobileLoginForm')" style="width: 100%;background: #409EFF">登录</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane> -->
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import dbl from "@/utils/dbl";
import { encrypt } from "@/utils/rsaEncrypt";
import { fetchAllList } from "~/admin/api/dict";
import { login, getMenu, getCodeImg, getPhoneCodeImg, Phonelogin } from "@/api/login";
import slider from '@/views/login/components/slider.vue';
const loginBg = require('@/assets/images/login_bg.jpg');
import Cookies from "js-cookie";

export default {
  name: "Login",
  components: {
    slider
  },
  data () {
    return {
      loginBg,
      loading: false,
      loadingText: '正在加载验证码',
      redirect: undefined,
      // 电话验证码
      show: false,
      // 标签页
      activeName: 'first',
      //校验码图片地址
      codeUrl: '',
      // 表单
      loginForm: {
        username: process.env.NODE_ENV === 'development' ? 'admin' : '',
        telnumber: '',
        password: process.env.NODE_ENV === 'development' ? '123zxc!@' : '',
        telcode: '',
        code: '',
        uuid: ''
      },
      // 手机登陆表单
      mobileLoginForm: {
        telnumber: process.env.NODE_ENV === 'development' ? '17034642999' : '',
        password: process.env.NODE_ENV === 'development' ? '123zxc!@' : '',
        telcode: '',
        uuid: ''
      },
      // 表单验证，需要在 el-form-item 元素中增加 prop 属性
      rules: {
        username: [{ required: true, message: '账号不可为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不可为空', trigger: 'blur' }],
        code: [{ required: true, message: '验证码不可为空', trigger: 'blur' }],
      },
      mobileLoginFormRules: {
        telnumber: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不可为空', trigger: 'blur' }],
        telcode: [{ required: true, message: '验证码不可为空', trigger: 'blur' }],
      }
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created () {
    this.getCode();
  },
  methods: {
    phoneCode () {
      if (this.mobileLoginForm.telnumber == null || this.mobileLoginForm.telnumber == '') {
        this.$message.info("请输入手机号码");
        return;
      }
      getPhoneCodeImg(this.mobileLoginForm.telnumber).then((res) => {
        this.mobileLoginForm.telcode = res.data.data.code;
        this.mobileLoginForm.uuid = res.data.data.uuid;
      });

    },
    // 电话验证码
    zdy (e) {
      this.show = e
    },
    onSubmit (formName = 'loginForm') {
      // 为表单绑定验证功能
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.login()
        } else {
          this.dialogVisible = true
          return false
        }
      })
    },
    PhoneOnSubmit (formName = 'mobileLoginForm') {
      // 为表单绑定验证功能
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.Phonelogin()
        } else {
          this.dialogVisible = true
          return false
        }
      })
    },
    getCode () {
      this.loading = true;
      this.loadingText = "正在加载验证码";
      getCodeImg().then((res) => {
        this.loading = false;
        this.codeUrl = res.data.data.img;
        this.loginForm.uuid = res.data.data.uuid;
      });
    },
    Phonelogin () {
      this.loading = true;
      this.loadingText = "登录中……";
      const user = {
        telnumber: this.mobileLoginForm.telnumber,
        password: this.mobileLoginForm.password,
        rememberMe: false,
        code: this.mobileLoginForm.telcode,
        uuid: this.mobileLoginForm.uuid,
      };
      var pwFlag = false; //false:密码满足复杂度要求 true：密码不满足复杂度要求，需要修改
      var pwdRegex = new RegExp(
        "(?=.*\\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&*()]).{8,15}"
      );
      if (!pwdRegex.test(user.password)) {
        pwFlag = true;
      }
      if (user.password !== this.cookiePass) {
        user.password = encrypt(user.password);
      }
      Phonelogin(user.telnumber, user.password, user.code, user.uuid)
        .then((resp) => {
          let data = resp.data.data;
          let token = data.token;
          let roles = data.user.roles;
          let userInfo = data.user.user;
          userInfo.deptId = data.user.deptId;
          userInfo.deptName = data.user.deptName;
          userInfo.deptCascadeCode = data.user.deptCascadeCode;

          this.$store.commit("SET_USER", userInfo);
          this.$store.commit("SET_ROLES", roles);

          dbl.set("token", token);
          Cookies.set("dbl-user", JSON.stringify(userInfo), { expires: 30 });
          dbl.set("roles", roles);
          dbl.set("user", userInfo);
          if (pwFlag) {
            alert("密码复杂度不够，请先修改密码！");
            this.$router.push(
              "/editPassword?userId=" +
              userInfo.userId +
              "&username=" +
              user.username
            );
          } else {
            this.getDictData();
            this.$store.dispatch("init");
          }
        })
        .catch(() => {
          this.loading = false;
          this.getCode();
        });
    },
    login () {
      const user = {
        username: this.loginForm.username,
        password: this.loginForm.password,
        rememberMe: false,
        code: this.loginForm.code,
        uuid: this.loginForm.uuid,
      };
      var pwFlag = false; //false:密码满足复杂度要求 true：密码不满足复杂度要求，需要修改
      var pwdRegex = new RegExp(
        "(?=.*\\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&*()]).{8,15}"
      );
      if (!pwdRegex.test(user.password)) {
        pwFlag = true;
      }
      if (user.password !== this.cookiePass) {
        user.password = encrypt(user.password);
      }
      this.loading = true;
      this.loadingText = "登录中……";
      login(user.username, user.password, user.code, user.uuid)
        .then((resp) => {
          let data = resp.data.data;
          let token = data.token;
          let roles = data.user.roles;
          let userInfo = data.user.user;
          userInfo.deptId = data.user.deptId;
          userInfo.deptName = data.user.deptName;
          userInfo.deptCascadeCode = data.user.deptCascadeCode;

          this.$store.commit("SET_USER", userInfo);
          this.$store.commit("SET_ROLES", roles);

          dbl.set("token", token);
          dbl.set("roles", roles);
          dbl.set("user", userInfo);
          Cookies.set("dbl-user", JSON.stringify(userInfo), { expires: 30 });
          Cookies.set("dbl-token", JSON.stringify(token), { expires: 30 });
          if (pwFlag) {
            alert("密码复杂度不够，请先修改密码！");
            this.$router.push(
              "/editPassword?userId=" +
              userInfo.userId +
              "&username=" +
              user.username
            );
          } else {
            this.getDictData();
            this.$store.dispatch("init");
          }
        })
        .catch(() => {
          this.loading = false;
          this.getCode();
        });

    },
    getDictData () {
      fetchAllList().then((resp) => {
        let list = resp.data.data;
        dbl.set("dict", list);
        this.$store.state.dict = list;
        this.getUserMenu();
      });
    },
    getUserMenu () {
      getMenu()
        .then((resp) => {
          this.loading = false;
          this.$message({
            showClose: true,
            message: "登录成功",
            type: "success",
            offset: 70,
          });

          let list = resp.data.data;
          dbl.set("menus", list);
          this.$store.commit("SET_MENU", list);
          let first = list[0];
          console.log("router", first);
          // 如果是掉线后登陆的话，判断缓存中是否有掉线前的地址，有的话就跳转过去
          let lastUrl = localStorage.getItem("lastUrl");
          if (lastUrl) {
            localStorage.removeItem("lastUrl");
            window.location.href = window.location.origin + lastUrl;
          } else {
            if (first.children && first.children.length > 0) {
              let second = first.children[0];
              // 这里设置路由跳转
              console.log("🚀 ~ file: index.vue ~ line 346 ~ .then ~ first", first)
              console.log("🚀 ~ file: index.vue ~ line 347 ~ .then ~ second", second)
              if (second.children && second.children.length > 0) {
                //this.$router.replace({path: second.children[0].path})
                this.$router.replace({ path: "/index" });
              } else {
                this.$router.replace({ path: second.path });
              }
            } else {
              this.$router.replace({ path: first.path });
            }
          }
        })
        .catch((err) => {
          this.err("菜单获取错误，请联系管理员");
        });
    },
  },
};
</script>

<style scoped lang="scss">
.logincontend {
  min-width: 100vw;
  position: absolute;
  width: 100%;
  height: calc(100vh) !important;
  top: 0;
  left: 0;
  bottom: 0;
  overflow-x: hidden;
  margin: 0px;
  padding: 0px;
  border-bottom: none;
  background-position: center;
  -webkit-background-size: cover;
  background-size: cover;
  background-repeat: no-repeat;

  .form-wrapper {
    margin-top: 50px;
    width: 100%;
  }

  .logoimg {
    margin: 10% 0px;
    text-align: center;
    .name {
      font-size: 22px;
      font-weight: bold;
      color: #333;
    }

    img {
      width: 60%;
    }
  }

  .el-button--medium {
    padding: 12px 20px;
    font-size: 16px;
  }

  /deep/.el-button {
    border-radius: 0;
  }

  /deep/.el-tabs__nav-wrap::after {
    height: 0px;
  }

  /deep/.el-tabs__content {
    overflow: inherit;
  }

  /deep/.el-input-group__append,
  .el-input-group__prepend {
    border-left: 0;
    border-right: 0;
    border-top: 0;

    span {
      font-size: 12px !important;
    }
  }

  .el-divider--vertical {
    margin: 0px 16px;
  }

  .el-form {
    margin-top: 10%;

    /deep/.el-input__inner {
      border: 0px;
      border-bottom: 1px solid #dcdfe6;
    }
  }

  h1,
  h3 {
    margin-bottom: 0rem;
    font-weight: 300;
  }

  h3 {
    margin-bottom: 1rem;
  }

  h1.login-title {
    color: #fff;
    font-size: 36px;
    margin-top: 10%;
  }

  .el-divider {
    background: #f6f6f6;
  }

  .el-dialog__body {
    height: inherit !important;
  }

  .el-link.el-link--default {
    color: #fff;
  }
}

.login-box {
  padding: 25px 35px;
  border-radius: 0;
  height: 100vh;
  border: 0px;
  /deep/ .el-input-group__append {
    width: 100px;
    height: 100%;
    padding: 0;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
